window.onload = function (){
    cutAll(1);
}

/**
 * 分页显示订单数据
 * @param pageNO 页码
 */
function cutAll(pageNO){
    axios.get("/order/cutAll",{
        params:{
            pageNO:pageNO
        }
    }).then(resp =>{
        var info =resp.data;
        var str = "";
        info.list.forEach(n => {
            str += `<tr><td>${n.userName}</td><td>${n.orderDate}</td>
            <td>${n.address}</td><td><a href="javascript:del(${n.id})">删除</a>
            <a href="javascript:findById(${n.id})">修改</a></td></tr>`;
        });
        $("data").innerHTML = str;

        var cutStr = "";
        for(var i=1;i<=info.totalPage;i++){
            cutStr += `<a href="javascript:cutAll(${i})" style="margin-left: 10px">${i}</a>`;
        }
        $("cutDiv").innerHTML = cutStr;
    });
}

function $(id){
    return document.getElementById(id);
}

/**
 * 删除订单
 * @param id 订单ID
 */
function del(id){
    axios.get("/order/del",{
        params:{
            id
        }
    }).then(resp =>{
        var info = resp.data;
        if(info == "ok"){
            cutAll(1);
        }
    })
}

/**
 * 显示添加弹出框
 */
function showAddDiv(){
    $("addDiv").style.visibility = "visible";
}

/**
 * 添加订单
 */
function addOrder(){
    // axios.get("/order/add",{
    //     params:{
    //         userName:$("userName").value,
    //         address:$("address").value
    //     }
    // }).then(resp =>{
    //     var info = resp.data;
    //     if(info == "ok"){
    //         cutAll(1);
    //         $("userName").value = null;
    //         $("address").value = "";
    //         $("addDiv").style.visibility = "hidden";
    //     }
    // });


    let paramObj = new URLSearchParams();
    //添加表单数据
    paramObj.append("userName",$("userName").value);
    paramObj.append("address",$("address").value);

    //向服务器发送AJAX的POST请求
    axios.post("/order/add",paramObj).then(
        resp =>{
                var info = resp.data;
                if(info == "ok"){
                    cutAll(1);
                    $("userName").value = null;
                    $("address").value = "";
                    $("addDiv").style.visibility = "hidden";
                }
            }
    );
}

/**
 * 按ID查询
 * @param id 订单ID
 */
function findById(id){
    axios.get("/order/findById",{
        params:{
            id
        }
    }).then(resp =>{
        var info = resp.data;
        //将对象数据显示在界面中
        $("nameSpan").innerHTML = info.userName;
        $("updateAddress").value = info.address;
        $("id").value = info.id;

        $("updateDiv").style.visibility = "visible";
    })
}

/**
 * 修改订单
 */
function updateOrder(){
    axios.get("/order/update",{
        params:{
            id:$("id").value,
            address:$("updateAddress").value
        }
    }).then(resp => {
        var info = resp.data;
        if(info == "ok"){
            cutAll(1);
            $("updateDiv").style.visibility = "hidden";
        }
    });
}